package com.struggle.myrabbitmq.sample.common;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import lombok.SneakyThrows;

/**
 * @className RecvUtil
 * @Description TODO
 * @Author liuwj3
 * @Date 2019/10/9 0009 下午 4:45
 **/
public class RecvUtil {
    private RecvUtil() {}

    /**
     * 得到消息
     * @param channel 消息通道
     * @param recvName 消费者名字
     * @param needAck 是否需要手动确认
     * @return
     */
    public static DeliverCallback getDeliverCallback(Channel channel, String recvName, final boolean needAck) {
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            byte[] body = delivery.getBody();
            String message = new String(body);
            System.out.println(" [" + recvName + "] Received '" + message + "'");
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
            if (needAck) {
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        return deliverCallback;
    }

}
